package com.qlu.syq.service.impl;

import com.qlu.syq.dao.BookOrderDao;
import com.qlu.syq.dao.RoomTypeDao;
import com.qlu.syq.dao.admin.FloorDao;
import com.qlu.syq.dao.admin.PlaceDao;
import com.qlu.syq.dao.admin.RoomDao;
import com.qlu.syq.entity.BookOrder;
import com.qlu.syq.entity.RoomType;
import com.qlu.syq.entity.admin.Place;
import com.qlu.syq.entity.admin.Room;
import com.qlu.syq.service.HomeBookService;
import com.qlu.syq.util.DistanceUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: HomeBookServiceImpl
 * @Description: 前台预订Service
 * @Author: ZPF
 * @Date: 2021/5/21 16:40
 **/
@Service
public class HomeBookServiceImpl implements HomeBookService {

    @Autowired
    PlaceDao placeDao;
    @Autowired
    FloorDao floorDao;
    @Autowired
    BookOrderDao bookOrderDao;
    @Autowired
    RoomDao roomDao;
    @Autowired
    RoomTypeDao roomTypeDao;


    /***
     * @MethodName: matchingFloorByPlaceId
     * @Description: 通过考点id匹配酒店
     * @Author: ZPF
     * @Date: 2021/5/21 16:53
     **/
    @Override
    public List<Map<String, Object>> matchingFloorByPlaceId(Integer placeId) {

        Place place = placeDao.find(placeId);
        double longitude = place.getLongitude();
        double latitude = place.getLatitude();

        List<Map<String, Object>> FloorLists = floorDao.queryAllFloorAvilableNum();

        for (Map<String, Object> floor : FloorLists) {
            double longitude1 = (double) floor.get("longitude");
            double latitude1 = (double) floor.get("latitude");
            double distance = DistanceUtil.getDistance(longitude, latitude, longitude1, latitude1);
            floor.put("distance", distance);
        }

        Collections.sort(FloorLists, (a, b) -> (int) ((double)a.get("distance") - (double)b.get("distance")));

        return FloorLists;
    }

    @Override
    @Transactional
    public int bookOrder(BookOrder bookOrder) throws Exception {
        // 修改房间avilableNum
        Long roomTypeId = bookOrder.getRoomTypeId();
        RoomType roomType = roomTypeDao.find(roomTypeId);
        Integer avilableNum = roomType.getAvilableNum();
        if (avilableNum <= 0) {
            throw new Exception("该房型无剩余房间");
        }
        roomType.setAvilableNum(roomType.getAvilableNum() - 1);
        roomType.setBookNum(roomType.getBookNum() + 1);
        roomTypeDao.updateNum(roomType);
        // 添加预约记录
        return bookOrderDao.add(bookOrder);
    }

    @Override
    public List<RoomType> getRoomTypeList(Map<String, Object> map) {
        return roomTypeDao.findList(map);
    }

    @Override
    public List<Room> getRoomList(Map<String, Object> queryMap) {
        return roomDao.findList(queryMap);
    }
}
